// server/api/repositories.post.ts
import { defineEventHandler, readBody } from 'h3'
import { verifyToken } from '../utils/auth'
import prisma from '../utils/prisma'
export default defineEventHandler(async (event) => {
  try {
    // Token 验证（同上）
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({ statusCode: 401, message: '未提供认证令牌' })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({ statusCode: 401, message: '令牌无效或已过期' })
    }
    
    const body = await readBody(event)
    const { username, giteeUrl, remark } = body
    
    if (!username || !giteeUrl) {
      throw createError({ statusCode: 400, message: '用户名和仓库地址为必填项' })
    }
    
    // 查找用户
    const user = await prisma.user.findUnique({
      where: { username }
    })
    
    if (!user) {
      throw createError({ statusCode: 404, message: '用户不存在' })
    }
    
    // 创建仓库记录
    const repository = await prisma.repository.create({
      data: {
        giteeUrl,
        remark,
        userId: user.id
      }
    })
    
    return {
      code: 201,
      message: '创建成功',
      data: repository
    }
    
  } catch (error: any) {
    throw createError({
      statusCode: error.statusCode || 500,
      message: error.message || '创建失败'
    })
  }
})